addEventListener("fetch", (event) => {
  event.respondWith(handleRequest(event.request));
});

// 主处理函数
async function handleRequest(request) {
  const url = new URL(request.url);
  const userAgent = request.headers.get("User-Agent") || "";

  // 判断是否为 页面 请求
  const isPageRequest = (
    (request.headers.get("Accept") && request.headers.get("Accept").includes("text/html"))
  );
  


  // 判断设备类型
  const isMobile = /Mobile|Android|iPhone|BlackBerry|IEMobile|Opera Mini/i.test(
    userAgent
  );
  const isTablet = /iPad|Tablet|Kindle/i.test(userAgent);

  // CORS 头部
  const corsHeaders = {
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
    "Access-Control-Allow-Headers": "Content-Type, Authorization",
    "Access-Control-Allow-Credentials": "true",
  };

  // 处理预检请求
  if (request.method === "OPTIONS") {
    return new Response(null, {
      status: 204,
      headers: corsHeaders,
    });
  }

  // HTML 模板
  const htmlTemplate = (deviceType) => `
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta name="referrer" content="no-referrer">
        <title>api</title>
        <link
          rel="stylesheet"
          href="https://gitee.com/li-jiazhen0623/some-file/raw/master/imageApi.css"
        />
      </head>
      <body>
        <script referrerpolicy="no-referrer" src="https://gitee.com/li-jiazhen0623/some-file/raw/master/imageApi.js"></script>
      </body>
    </html>`;

  try {
    // 如果是 API 请求，根据路径处理逻辑
    if (!isPageRequest) {
      if (url.pathname === "/vertical") {
        // 竖屏逻辑
        const response = await fetch(
          "https://api.jiazhen.wang/api/verticalJson"
        );
        if (response.ok) {
          const data = await response.json();
          if (data.url) {
            return new Response(null, {
              status: 302,
              headers: { Location: data.url, ...corsHeaders },
            });
          }
        }
        return new Response("Failed to fetch vertical data", {
          status: 500,
          headers: corsHeaders,
        });
      } else if (url.pathname === "/horizontal") {
        // 横屏逻辑
        const response = await fetch(
          "https://api.jiazhen.wang/api/horizontalJson"
        );
        if (response.ok) {
          const data = await response.json();
          if (data.url) {
            return new Response(null, {
              status: 302,
              headers: { Location: data.url, ...corsHeaders },
            });
          }
        }
        return new Response("Failed to fetch horizontal data", {
          status: 500,
          headers: corsHeaders,
        });
      } else if (url.pathname === "/adaptive") {
        // 自适应逻辑
        const apiUrl =
          isMobile && !isTablet
            ? "https://api.jiazhen.wang/api/verticalJson"
            : "https://api.jiazhen.wang/api/horizontalJson";

        const response = await fetch(apiUrl);
        if (response.ok) {
          const data = await response.json();
          if (data.url) {
            return new Response(null, {
              status: 302,
              headers: { Location: data.url, ...corsHeaders },
            });
          }
        }
        return new Response("Failed to fetch adaptive data", {
          status: 500,
          headers: corsHeaders,
        });
      }
    }else if (
      url.pathname === "/adaptive" ||
      url.pathname === "/horizontal" ||
      url.pathname === "/vertical"
    ) {
      // 非 API 请求返回 HTML 模板
      const deviceType = isMobile && !isTablet ? "mobile" : "desktop";
      return new Response(htmlTemplate(deviceType), {
        headers: {
          "Content-Type": "text/html",
          ...corsHeaders,
        },
      });
    }
  } catch (error) {
    console.error("Error handling request:", error);
    return new Response("Internal Server Error", {
      status: 500,
      headers: corsHeaders,
    });
  }

  // 如果没有匹配的路径，返回 404
  return new Response("Not Found", {
    status: 404,
    headers: corsHeaders,
  });
}
